﻿using EMC.VISITOR.Application;
using EMC.VISITOR.ApplicationExtend.VisitorFlow;
using EMC.VISITOR.Core;
using Microsoft.AspNetCore.Mvc;
using OfficeOpenXml.FormulaParsing.Excel.Functions.DateTime;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using System.Web;

namespace EMC.VISITOR.ApplicationExtend
{
    public class VistorManage : IVistorManage
    {
        ISqlSugarClient _db;
        private IHttpClient _http;
        public VistorManage(SqlSugarRepository<VisitLog> rep, IHttpClient http)
        {
            _db = rep.Context;
            _http = http;
        }
        public async Task<JRResult<bool>> CheckVisitIDCard(AddVisitLogInput visit)
        {
            return CustomeResult.Success<bool>(true);
        }

        public async Task<JRResult<bool>> CheckVIstorCode(AddVisitLogInput visit)
        {
            var phoneCode = await _db.MyQueryable<VistorPhoneCode>().FirstAsync(r => r.Phone == visit.Iphone.Trim() && r.EndTime < DateTime.Now);
            if (phoneCode == null)
                return CustomeResult.Fail<bool>($"验证码已过期或其它原因，请重复发送验证码！");

            if (!phoneCode.Code.Trim().Equals(visit.PhoneCheckCode))
                return CustomeResult.Fail<bool>("输入的验证码错误！");

            return CustomeResult.Success<bool>();
        }

        [HttpGet]
        public async Task<JRResult<bool>> SendCheckCodePhoneMessage(string phone, string code, string content, int minute)
        {
            //TODO 调用第三方发送短信接口
            string message = HttpUtility.UrlEncode($"您的验证码是{code}。如非本人操作，请忽略本短信,10分钟内有效。");

            string url = $"http://sms-cly.cn/smsSend.do?username=cxjg&password=afcdc98eccdc52aca7cc2a3056d07c6a&mobile=13524093704&content={message}";
            var response = await _http.GetStringAsync(url);
            VistorPhoneCode phoneCode = new VistorPhoneCode();
            phoneCode.Phone = phone;
            phoneCode.Code = code;
            phoneCode.EndTime = DateTime.Now.AddMinutes(minute);
            var exsitPhoneCode = await _db.MyQueryable<VistorPhoneCode>().FirstAsync(r => r.Phone == phone && r.EndTime < phoneCode.EndTime);
            if (exsitPhoneCode != null)
                return CustomeResult.Fail<bool>($"勿重复发送验证码，验证码有效期为{minute}分钟！");

            await _db.MyInsertable<VistorPhoneCode>(phoneCode).ExecuteCommandAsync();
            return CustomeResult.Success<bool>();
        }
    }
}
